package com.tungse.netty2.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author : Tungse
 * @Date: 2025/7/5 10:07
 * @Description:
 */
public class Netty2Server {

    public static void main(String[] args) {
        Map<Channel, List<String>> db = new ConcurrentHashMap<>();


        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new LineBasedFrameDecoder(1024))
                                .addLast(new StringDecoder())
                                .addLast(new StringEncoder())
                                .addLast(new ResponseHandler())
                                .addLast(new DbHandler(db))
                        ;
                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind(8080);
        channelFuture.addListener(f -> {
            if (f.isSuccess()) {
                System.out.println("server start success");
            } else {
                System.out.println("server start fail");
            }
        });
    }

    static class ResponseHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println(msg);
            String message = msg + "world\n";
            ctx.channel().writeAndFlush(message);
            ctx.fireChannelRead(msg);
        }
    }
    static class DbHandler extends SimpleChannelInboundHandler<String> {
        Map<Channel, List<String>> db;
        public DbHandler(Map<Channel, List<String>> db) {
            this.db = db;
        }

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println("客户端注册" + ctx.channel().remoteAddress());
        }

        @Override
        public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println("客户端解除注册" + ctx.channel().remoteAddress());
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("客户端激活" + ctx.channel().remoteAddress());
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            List<String> stringList = db.get(ctx.channel());
            System.out.println("客户端断开连接" + ctx.channel().remoteAddress() + "消息" + stringList);
        }


        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            List<String> stringList = db.computeIfAbsent(ctx.channel(),
                    k -> new ArrayList<>());
            stringList.add(msg);
        }
    }

}
